package com.yurun.filemodule.service.Impl;

import com.yurun.filemodule.mapper.FileUploadMapper;
import com.yurun.filemodule.service.FileUploadService;
import com.yurun.filemodule.utils.FileUploadUtils;
import com.yurun.filemodule.utils.FileUtils;
import com.yurun.commonapi.pojo.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private FileUploadMapper fileUploadMapper;


    @Override
    public void upload(MultipartFile file, String baseDir) throws Exception {
        //就算什么也不传，controller层的file也不为空，但是originalFilename会为空（亲测）
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        if(originalFilename == null || "".equals(originalFilename)) {
            System.out.println("空");
            throw new Exception( "上传文件不能为空");
        }

        //新的文件
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileUpTime(new Date());
        fileUpload.setFileName(file.getOriginalFilename());        //这边可以根据业务修改，项目中不要写死
        fileUpload.setFileIfExist(1);
        String fileLocation = "";
        if(baseDir != null) {
            System.out.println("不为空");
            fileLocation = FileUploadUtils.upload(baseDir, file);
            System.out.println(fileLocation);
        }else {
            System.out.println("为空");
            fileLocation = FileUploadUtils.upload(file);
            System.out.println("哈哈哈"+fileLocation);
        }

        fileUpload.setFileAddress(fileLocation);
        fileUploadMapper.insert(fileUpload);
    }

    @Override
    public void download(HttpServletResponse response, Integer id) throws IOException {
        FileUpload fileUpload = fileUploadMapper.selectOneById(id);
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");        //这边可以设置文件下载时的名字，我这边用的是文件原本的名字，可以根据实际场景设置
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUpload.getFileName(), "UTF-8"));
        FileUtils.writeBytes(fileUpload.getFileAddress(), response.getOutputStream());
    }

    @Override
    public int deleteById(Integer id) {
        return fileUploadMapper.deleteById(id);
    }

    @Override
    public int deleteStatus(Integer id) {
        return fileUploadMapper.updateIfExistById(id);
    }

    /**
     *
     * @return 数据库存储的文件的总数
     */
    public Integer fileSize(){
        return fileUploadMapper.fileSize();
    }
}
